<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2018/4/23
 * Time: 下午10:46
 */

namespace common\logic;


use common\models\UserCouponModel;
use common\models\UserOrderModel;
use yii\db\ActiveQuery;

class UserCouponLogic extends Logic
{

    /**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return UserCouponModel::find();
    }

    /**
     * 分页
     *
     * @param        $page
     * @param int    $pageSize
     * @param array  $search
     *
     * @return array
     */
    public function getByPage($page, $uid, $pageSize = 20)
    {
        $nextPage = 0;
        $query = $this->_getActiveQuery()->joinWith('coupon');
        $tblUserCoupon = UserCouponModel::tableName();
        $offset = ($page - 1) * $pageSize;
        $query = $query->limit($pageSize + 1)->where(["$tblUserCoupon.user_id" => $uid,"$tblUserCoupon.used" => "0"])->offset($offset)->orderBy(["$tblUserCoupon.id" => SORT_DESC]);


        $data = $query->all();
        if (count($data) > $pageSize) {
            unset($data[$pageSize]);
            $nextPage = $page + 1;
        }
        $list = [];
        foreach ($data as $item) {
            $data = $item->toArray();
            $coupon = $item['coupon']->toArray(['name','code','denomination']);

            $data['name'] = $coupon['name'];
            $data['denomination'] = $coupon['denomination'];
            $data['create_time'] = date('Y-m-d H:i:s', $data['create_time']);
            $list[] = $data;
        }

        return ['nextPage' => $nextPage, 'list' => $list];
    }


    public function addUserCoupon($order_sn)
    {
        $order = UserOrderModel::findOne(['order_sn' => $order_sn]);
        if(empty($order)){
            return false;
        }
        if (!empty($order) && empty($order->pay_status)) {
            $order->pay_status = 1;
            $order->pay_time = time();
        }

        $coupon = new UserCouponModel();
        $coupon->coupon_id = $order->coupon_id;
        $coupon->user_id = $order->user_id;
        $coupon->create_time = time();
        $coupon->code = time() . rand(10000, 99999);
        return $this->transaction(function () use ($order, $coupon) {
            if (!$order->save()) {
                return false;
            }
            if (!$coupon->save()) {
                return false;
            }

            return true;
        });
    }

}